<?php

namespace App\Models;


use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use App\Service\Base\Model;

class Article extends Model
{

    // 用户管理
    protected $table = 'article';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'cate_id', 'site_id', 'from_site', 'from_channel', 'verify', 'keyword', 'channel', 'feeling', 'sentiment'];

    // 获取所有的文章
    public function getChannels($getKey = true)
    {
        $channels = ['thread' => '帖子', 'article' => '文章', 'notice' => '公告', 'dispatch' => '快讯',];
        if(empty($getKey)){
            return $channels;
        }

        return array_keys($channels);
    }

    // 添加
    public function oneAdd($data = [])
    {
        // 验证信息
        $rules  = $this->fieldRule();
        $result = $this->validator($data, $rules, ['id' => '修改的用户编号']);
        if($result === false){
            return false;
        }
        /*if(empty($uid)){
            return $this->return_false('请指定发帖用户!');
        }
        if(empty($data['content'])){
            //return $this->return_false('请填写内容!');
        }*/

        // 模型
        $userDb = new User();
        $uid    = $data['uid'] ?? 0;

        // 整理数据
        //   阿特的用户 与 转发的数据
        $userDataAdd = ['article_no' => DB::raw('article_no'.'+1'), "publish_no" => DB::raw('publish_no+1'), 'mtime' => LARAVEL_TIME];

        // 模型数据
        $articleData = $this->filterField($data);
        $this->fill($articleData);
        // 保存数据
        DB::beginTransaction();
        try{

            // 添加
            $this->save();
            $aId = $this->id;

            // 更新用户发帖数量
            if($userDataAdd && $uid){
                $userDb->where('id', $uid)->update($userDataAdd);
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($data);
        $userDb->deleteCacheShow(['id' => $uid]);

        return $this->id;
    }

    // 获取某个时间段（一天内）的数据
    public function getArticleInTime($beginTime, $endTime)
    {
        // 获取所有的站点
        //$sites = (new SiteDomain())->isCache(true)->getList([], 0);
        $sites = (new SiteDomain())->get()->toArray();
        $sites = array_column($sites, null, 'id');
        // 获取数据
        $where  = [['push_time', '>=', $beginTime], ['push_time', '<=', $endTime], ['verify', '=', 1]];
        $lists  = $this->getList($where, 0);
        $nLists = [];
        foreach($lists as $item){
            $site_id = $item['site_id'];
            // 整理
            $nLists[$site_id]['news'][] = $item;
            $nLists[$site_id]['site']   = $sites[$site_id];
        }

        return $nLists;
    }

    // 修改
    // TODO 栏目话题可以是多个的数组，也可以是单个字符串（不能是多个组合的字符串）
    public function oneEdit($where, $data)
    {
        // 查询
        $info = $this->isCache(true)->oneFind($where);  // ->recycle()
        if(empty($info)){
            return $this->return_false('你要修改的数据不存在！！');
        }

        $info       = is_object($info) ? $info->toArray() : $info;
        $article_id = $info['id'];

        // 数据
        $articleData = $this->filterField($data);

        // 文章话题数据
        // 以前的数据 与 现在的数据 （话题是多个）
        $userMain = new User();
        // 文章数量
        //$addNumData = ['article_no' => DB::raw("article_no+1"), 'publish_no' => DB::raw("publish_no+1"),];
        //$decNumData = ['article_no' => DB::raw("article_no-1"), 'publish_no' => DB::raw("publish_no-1"),];

        // 保存数据
        DB::beginTransaction();
        try{
            /*// 如果有置顶
            if($is_top){
                // 取消其他置顶
                $result = $this->where(['is_top' => $is_top])->update(['is_top' => 0]);
            }*/

            // 主表
            $result = $this->where('id', $article_id)->update($articleData);


            // 用户文章数量
            /*if($old_uid != $uid){
                $result = $userMain->where('id', $uid)->update($addNumData);
                $result = $userMain->where('id', $old_uid)->update($decNumData);
            }*/

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($info, $data);

        return $result;
    }

    // 详情
    public function oneFind($where, $order = "id DESC")
    {
        // 获取缓存
        $is_cache = $this->is_cache || $this->bang;
        $args     = compact('where', 'order');
        $info     = null;
        if($is_cache){
            $cacheName = $this->cacheKey('show', $args);
            $info      = $this->cacheClass()->getCache($cacheName);
        }
        // 检查是否已经绑定
        if($info){
            $this->checkBangShow($info, $cacheName);
        }
        // 查询
        if(empty($info)){
            //  查询
            $query = $this->where($where);
            if(is_array($order)){
            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $info = $query->first(); // ->recycle()
            if(empty($info)){
                return $this->return_false('数据不存在！！');
            }
            // 组合
            $info = $info->toArray();
            // 保存为缓存
            if($is_cache){
                $this->addCacheShow($info, $cacheName, $info);
            }
        }

        // 编辑
        $info['user'] = [];
        if($info['uid']){
            $info['user'] = (new User())->isCache(true)->getOneById($info['uid']);
        }

        return $info;
    }

    // 获取多条数据+翻页
    public function listPage($where = [], $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists', $args);
            $cacheData = $this->cacheClass()->getCache($cacheName);
            if(!empty($cacheData)){
                // 检查是否已经绑定
                if(($cacheData) && (!empty($cacheData['list']))){
                    $this->checkBangList($cacheData['list'], $cacheName);
                }

                return $cacheData;
            }
        }

        // 字段
        $fields    = $this->inFields;
        $outFields = $this->outFields;
        if(empty($fields)){
            $fields = $this->getTableField(true);
        }
        if(is_string($fields)){
            $fields = explode(",", $fields);
        }
        if($outFields){
            if(is_string($outFields)){
                $outFields = explode(",", $outFields);
            }
            $fields = array_diff($fields, $outFields);
        }

        $all_size = $rows + 1;
        if(empty($where)){
            $query = $this->select($fields)->forPage($page, $rows);
            $count = $this->count();
        } else{
            if(is_array($where)){
                // 查询  ->recycle()  ->orderby($order)
                $query = $this->where($where)->select($fields)->forPage($page, $rows);
                $count = $this->where($where)->count();
            } elseif(is_string($where)){
                // 查询  ->recycle()  ->orderby($order)
                $query = $this->whereRaw($where)->select($fields)->forPage($page, $rows);
                $count = $this->whereRaw($where)->count();
            } /*else{
                // 查询  ->recycle()  ->orderby($order)
                $query = $where->select($fields)->forPage($page, $rows);
                $count = $where->count();
            }*/
        }


        if(is_array($order)){
            $query = $query->orderBy($order[0], $order[1]);
        } else{
            $query = $query->orderByRaw($order);
        }

        // 查找过滤
        $is_next = 0;
        $lists   = $query->get()->toArray();
        // 查看是否需要翻页
        if($page * $rows < $count){
            $is_next = 1;
        }

        // 过滤json
        $jsonField = isset($this->jsonField) ?: '';
        if(!empty($jsonField)){
            $jsonField = is_string($jsonField) ? explode(',', $jsonField) : $jsonField;
            foreach($lists as $_list){
                foreach($jsonField as $_field){
                    $_list->$_field = json_decode($_list->$_field, 1);
                }
            }
        }

        // 返回编辑作者
        $uids = array_unique(array_column($lists, 'uid'));
        if($uids){
            $userDb = new User();
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($lists as &$item){
                $_uid = $item['uid'];
                // 整理
                $item['user'] = $users[$_uid] ?? [];
                // 头像
                if($item['user']){
                    $item['user']['head_img'] = $this->getFullUrl($item['user']['head_img']);
                }
            }
        }


        $result = ['total' => $count, 'page' => $page, 'rows' => $rows, 'is_next' => $is_next, 'list' => $lists,];
        // 保存为缓存
        if($is_cache){
            $this->addCacheList($lists, $cacheName, $result, 'list');
        }

        return $result;
    }

    // 删除文章
    public function softDelete($where)
    {
        $lists = $this->isCache(true)->getList($where);  //->recycle()
        if(empty($lists)){
            return $this->return_false('你要删除的数据不存在！！');
        }

        $_ids = array_column($lists, 'id');
        if($_ids){
            $this->whereIn('id', $_ids)->update(['verify' => -1]);
        }

        $this->deleteCacheList($lists);
        $this->deleteCacheShow(['id' => $_ids, 'verify' => -1]);

        return true;
    }

    // 文件地址
    protected function getFullUrl($url)
    {
        if(!$url){
            return '';
        }

        if(substr($url, 0, 4) != 'http'){
            $domain = Config::get('site.cdnHost');
            $domain = substr($domain, -1) == '/' ? substr($domain, 0, -1) : $domain;
            $url    = $domain.$url;
        }

        return $url;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            // 详情
            // 'content'     => 'required',

            'title'        => 'required',
            'from_channel' => 'sometimes|required',
            'site_id'      => 'required',
            'from_site'    => 'required',
            'description'  => 'required',
            'from_url'     => 'required',
            'author'       => 'sometimes|required',
            //'keyword'     => 'required',
            'push_time'    => 'sometimes|required',
            'cover'        => 'sometimes|required',
            'uid'          => 'numeric',
            'cate_id'      => 'numeric',
            'read_no'      => 'numeric',
            'virtual_no'   => 'numeric',
            'praise_no'    => 'numeric',
            'collect_no'   => 'numeric',
            'relay_no'     => 'numeric',
            'comment_no'   => 'numeric',
            'is_top'       => 'numeric',
            'verify'       => ['in:0,1'],
            //'status'      => ['in:0,1,2'],
            //'is_original' => 'numeric',
            //'images'      => 'required',
        ];


        $msg = [
            'id'           => '自编号',
            'title'        => '标题',
            'uid'          => '用户id',
            'cover'        => '图片',
            'cate_id'      => '栏目id',
            'author'       => '作家',
            'site_id'      => '来源站点id',
            'from_site'    => '来源站点',
            'from_channel' => '来源频道',
            'keyword'      => '关键字',
            'description'  => '描述(现在快讯最多588个字)',
            'read_no'      => '浏览数',
            'virtual_no'   => '虚拟浏览数',
            'praise_no'    => '点赞数',
            'collect_no'   => '收藏数',
            'relay_no'     => '转发次数',
            'comment_no'   => '评论次数',
            'images'       => '图片集合',
            'verify'       => '是否审核（1-是，-1删除）',
            'ip'           => 'ip地址',
            'ip_address'   => 'ip的实际地址',
            'is_top'       => '是否置顶（1-是）',
            'is_push'      => '是否推送（1-是）',
            'from_url'     => '采集文章的来源地址',
            'push_time'    => '发布时间',
            'ctime'        => '创建时间',
            'mtime'        => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }

}
